package com.ruoyi.common.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.business.entity.YytBaseCatalog;
import com.ruoyi.common.business.entity.YytHomeSubject;
import com.ruoyi.common.business.entity.YytHomeSubjectSpu;
import com.ruoyi.common.business.service.YytBaseCatalogService;
import com.ruoyi.common.business.service.YytHomeSubjectService;
import com.ruoyi.common.business.service.YytHomeSubjectSpuService;
import com.ruoyi.common.elasticsearch.domain.EsSkuInfo;
import com.ruoyi.common.elasticsearch.domain.HotWordLables;
import com.ruoyi.common.elasticsearch.service.ElasticSearchService;
import com.ruoyi.common.pms.entity.*;
import com.ruoyi.common.pms.dao.YytPmsSpuInfoMapper;
import com.ruoyi.common.pms.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.vo.SkuInfoVo;
import com.ruoyi.vo.SpuInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* <p>
    * spu信息 服务实现类
    * </p>
*
* @author huangshun
* @since 2021-12-16
*/
@Service
public class YytPmsSpuInfoServiceImpl extends ServiceImpl<YytPmsSpuInfoMapper, YytPmsSpuInfo> implements YytPmsSpuInfoService {

    @Autowired
    private YytPmsSpuInfoDescService yytPmsSpuInfoDescService;
    @Autowired
    private YytPmsSpuImagesService yytPmsSpuImagesService;
    @Autowired
    private YytPmsSpuSaleAttrValueService yytPmsSpuSaleAttrValueService;
    @Autowired
    private YytHomeSubjectSpuService yytHomeSubjectSpuService;
    @Autowired
    private YytPmsSkuInfoService yytPmsSkuInfoService;
    @Autowired
    private YytPmsSkuImagesService yytPmsSkuImagesService;
    @Autowired
    private YytPmsSkuSaleAttrValueService yytPmsSkuSaleAttrValueService;
    @Autowired
    private YytPmsSpuInfoMapper yytPmsSpuInfoMapper;
    @Autowired
    private YytHomeSubjectService yytHomeSubjectService;
    @Autowired
    private YytPmsBrandService yytPmsBrandService;
    @Autowired
    private YytShopService yytShopService;
    @Autowired
    private YytBaseCatalogService yytBaseCatalogService;
    @Autowired
    private ElasticSearchService elasticSearchService;



    @Override
    public int insertYytPmsSpuInfo(SpuInfoVo SpuInfoVo){
        // 1、保存 spuInfo 信息
        YytPmsSpuInfo yytPmsSpuInfo = new YytPmsSpuInfo();
        yytPmsSpuInfo.setCreateTime(LocalDateTime.now());
        yytPmsSpuInfo.setBrandId(SpuInfoVo.getBrandId());
        yytPmsSpuInfo.setSpuName(SpuInfoVo.getSpuName());
        yytPmsSpuInfo.setCatalogId(SpuInfoVo.getCatalogId());
        yytPmsSpuInfo.setIsMoreSpec(SpuInfoVo.getIsMoreSpec2());
        yytPmsSpuInfo.setShopId(SpuInfoVo.getShopId());
        yytPmsSpuInfo.setSpuType("2");
        yytPmsSpuInfo.setAuditStatus("1");
        yytPmsSpuInfo.setWeight(SpuInfoVo.getWeight());
        yytPmsSpuInfo.setPublishStatus(Integer.parseInt(SpuInfoVo.getPublishStatus()));
        boolean save = super.save(yytPmsSpuInfo);
        //2.保存spuInfoDesc 详情信息
        YytPmsSpuInfoDesc yytPmsSpuInfoDesc = new YytPmsSpuInfoDesc();
        yytPmsSpuInfoDesc.setSpuId(yytPmsSpuInfo.getId());
        yytPmsSpuInfoDesc.setDecript(SpuInfoVo.getDescription());
        yytPmsSpuInfoDescService.save(yytPmsSpuInfoDesc);
        //3.保存图片图集yyt_pms_spu_images
        String[] supImages = SpuInfoVo.getSupImages().split(",");
        List<YytPmsSpuImages> yytPmsSpuImages = Arrays.stream(supImages).map(s -> {
            YytPmsSpuImages yytPmsSpuImage = new YytPmsSpuImages();
            yytPmsSpuImage.setSpuId(yytPmsSpuInfo.getId());
            yytPmsSpuImage.setImgUrl(s);
            yytPmsSpuImage.setDefaultImg(0);
            return yytPmsSpuImage;
        }).collect(Collectors.toList());
        yytPmsSpuImages.get(0).setDefaultImg(1);
        yytPmsSpuImagesService.saveBatch(yytPmsSpuImages);
        //4.保存销售属性 yyt_pms_spu_sale_attr_value
        List<YytPmsSpuSaleAttrValue> yytPmsSpuSaleAttrValues = SpuInfoVo.getSaleAttrs().stream().map(spuSaleAttrsVo -> {
            YytPmsSpuSaleAttrValue yytPmsSpuSaleAttrValue = new YytPmsSpuSaleAttrValue();
            yytPmsSpuSaleAttrValue.setAttrId(spuSaleAttrsVo.getAttrId());
            yytPmsSpuSaleAttrValue.setAttrName(spuSaleAttrsVo.getName());
            yytPmsSpuSaleAttrValue.setAttrValue(StringUtils.join(spuSaleAttrsVo.getValue(),","));
            return yytPmsSpuSaleAttrValue;
        }).collect(Collectors.toList());
        yytPmsSpuSaleAttrValueService.saveBatch(yytPmsSpuSaleAttrValues);
        // 5.保存关联专题
        if(SpuInfoVo.getSubjectIds()!=null && SpuInfoVo.getSubjectIds().size()>0){
            List<YytHomeSubjectSpu> yytHomeSubjectSpus = new ArrayList<>();
            for (String subjectId:SpuInfoVo.getSubjectIds()){
                YytHomeSubjectSpu yytHomeSubjectSpu = new YytHomeSubjectSpu();
                yytHomeSubjectSpu.setSubjectId(subjectId);
                yytHomeSubjectSpu.setSpuId(yytPmsSpuInfo.getId());
                yytHomeSubjectSpus.add(yytHomeSubjectSpu);
            }
            yytHomeSubjectSpuService.saveBatch(yytHomeSubjectSpus);
        }
        //5.积分信息---> 暂时不填
        //6.保存spu 对应sku 信息
        if (SpuInfoVo.getIsMoreSpec2().equals("0")) { // 单规格
            SkuInfoVo skuInfoVo = SpuInfoVo.getSkuInfo();
            skuInfoVo.setSkuName(SpuInfoVo.getSpuName());
            skuInfoVo.setSkuTitle(SpuInfoVo.getSpuName());
            saveSkuInfo(skuInfoVo, supImages, yytPmsSpuInfo,yytPmsSpuSaleAttrValues);
        } else if (SpuInfoVo.getIsMoreSpec2().equals("1")) { // 多规格
            //6.1 保存sku 基本信息
            for (SkuInfoVo skuInfoVo : SpuInfoVo.getSaleData()) {
                saveSkuInfo(skuInfoVo, supImages, yytPmsSpuInfo,yytPmsSpuSaleAttrValues);
            }
        }

        return 0;
    }


    /**
     * 方法名 saveSkuInfo
     * 描述 TODO 保存sku信息
     * 作者 黄顺
     * 时间 2021/12/16 14:14
     *
     * @Param [skuInfoVo, supImages]
     */
    public void saveSkuInfo(SkuInfoVo skuInfoVo, String[] supImages, YytPmsSpuInfo yytPmsSpuInfo,List<YytPmsSpuSaleAttrValue> yytPmsSpuSaleAttrValues) {
        //6.1 保存sku 基本信息
        YytPmsSkuInfo yytPmsSkuInfo = new YytPmsSkuInfo();
        BeanUtils.copyProperties(skuInfoVo,yytPmsSkuInfo);
        yytPmsSkuInfo.setSpuId(yytPmsSpuInfo.getId());
        yytPmsSkuInfo.setCatalogId(yytPmsSpuInfo.getCatalogId());
        yytPmsSkuInfo.setBrandId(yytPmsSpuInfo.getBrandId());
        yytPmsSkuInfo.setShopId(yytPmsSpuInfo.getShopId());
        if(StringUtils.isNotEmpty(skuInfoVo.getId())){
            yytPmsSkuInfo.setSkuId(skuInfoVo.getId());
            yytPmsSkuInfoService.updateById(yytPmsSkuInfo);
            //删除默认图片
            LambdaQueryWrapper<YytPmsSkuImages> yytPmsSkuImagesLambdaQueryWrapper = new LambdaQueryWrapper<>();
            yytPmsSkuImagesLambdaQueryWrapper.eq(YytPmsSkuImages::getSkuId,yytPmsSkuInfo.getSkuId());
            yytPmsSkuImagesService.remove(yytPmsSkuImagesLambdaQueryWrapper);
            //删除属性
            LambdaQueryWrapper<YytPmsSkuSaleAttrValue> yytPmsSkuSaleAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            yytPmsSkuSaleAttrValueLambdaQueryWrapper.eq(YytPmsSkuSaleAttrValue::getSkuId,yytPmsSkuInfo.getSkuId());
            yytPmsSkuSaleAttrValueService.remove(yytPmsSkuSaleAttrValueLambdaQueryWrapper);
        }else{
            yytPmsSkuInfoService.save(yytPmsSkuInfo);
        }

        //6.2 保存sku 图片图集
        List<YytPmsSkuImages> yytPmsSkuImages = Arrays.stream(supImages).map(s -> {
            YytPmsSkuImages yytPmsSkuImage = new YytPmsSkuImages();
            yytPmsSkuImage.setImgUrl(s);
            yytPmsSkuImage.setSkuId(yytPmsSkuInfo.getSkuId());
            yytPmsSkuImage.setDefaultImg(0);
            return yytPmsSkuImage;
        }).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(yytPmsSkuInfo.getSkuDefaultImg())) {
            YytPmsSkuImages yytPmsSkuImage = new YytPmsSkuImages();
            yytPmsSkuImage.setImgUrl(yytPmsSkuInfo.getSkuDefaultImg());
            yytPmsSkuImage.setSkuId(yytPmsSkuInfo.getSkuId());
            yytPmsSkuImage.setDefaultImg(1);
            yytPmsSkuImages.add(yytPmsSkuImage);
        } else {
            yytPmsSkuImages.get(0).setDefaultImg(1);
        }
        yytPmsSkuImagesService.saveBatch(yytPmsSkuImages);
        //6.3 保存sku 销售属性
        if (skuInfoVo.getAttrs() != null && skuInfoVo.getAttrs().size() > 0) {
            List<YytPmsSkuSaleAttrValue> yytPmsSkuSaleAttrValues = skuInfoVo.getAttrs().stream().map(attrs -> {
                YytPmsSkuSaleAttrValue yytPmsSkuSaleAttrValue = new YytPmsSkuSaleAttrValue();
                yytPmsSkuSaleAttrValue.setAttrValue(attrs.getValue());
                //获取spu_sale_attrId
                for (YytPmsSpuSaleAttrValue yytPmsSpuSaleAttrValue :yytPmsSpuSaleAttrValues){
                    if(attrs.getName().equals(yytPmsSpuSaleAttrValue.getAttrName())){
                        yytPmsSkuSaleAttrValue.setAttrId(yytPmsSpuSaleAttrValue.getId());
                    }
                }
                yytPmsSkuSaleAttrValue.setAttrName(attrs.getName());
                yytPmsSkuSaleAttrValue.setSkuId(yytPmsSkuInfo.getSkuId());
                return yytPmsSkuSaleAttrValue;
            }).collect(Collectors.toList());
            yytPmsSkuSaleAttrValueService.saveBatch(yytPmsSkuSaleAttrValues);
        }

        if(yytPmsSpuInfo.getPublishStatus().equals(1)){
            String[] ids = yytPmsSpuInfo.getId().split(",");
            upStatus(ids,"0");
        }

    }


    @Transactional
    public int upStatus(String[] ids, String type) {

        /** 获取需要上下架的商品 */
        LambdaQueryWrapper<YytPmsSpuInfo> yytPmsSpuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        yytPmsSpuInfoLambdaQueryWrapper.in(YytPmsSpuInfo::getId, ids).eq(YytPmsSpuInfo::getDelFlag, "0");
        List<YytPmsSpuInfo> yytPmsSpuInfos = yytPmsSpuInfoMapper.selectList(yytPmsSpuInfoLambdaQueryWrapper);



        List<EsSkuInfo> skuInfoList = new ArrayList<>();
        for (YytPmsSpuInfo iYytPmsSpuInfo : yytPmsSpuInfos) {
            iYytPmsSpuInfo.setPublishStatus(Integer.parseInt(type));
            //上架
            if (type.equals("1")) {
                //获取sku
                LambdaQueryWrapper<YytPmsSkuInfo> skuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                skuInfoLambdaQueryWrapper.eq(YytPmsSkuInfo::getSpuId, iYytPmsSpuInfo.getId());
                List<YytPmsSkuInfo> yytPmsSkuInfos = yytPmsSkuInfoService.list(skuInfoLambdaQueryWrapper);

                // 获取专题
                YytHomeSubjectSpu yytHomeSubjectSpu = new YytHomeSubjectSpu();
                yytHomeSubjectSpu.setSpuId(iYytPmsSpuInfo.getId());
                List<YytHomeSubjectSpu> yytHomeSubjectSpus = yytHomeSubjectSpuService.selectYytHomeSubjectSpuList(yytHomeSubjectSpu);
                List<HotWordLables> hotWordLablesList = new ArrayList<>();
                if(yytHomeSubjectSpus.size()>0){
                    List<String> subjectIds = yytHomeSubjectSpus.stream().map(yytHomeSubjectSpu1 -> {
                        return yytHomeSubjectSpu1.getSubjectId();
                    }).collect(Collectors.toList());
                    LambdaQueryWrapper<YytHomeSubject> yytHomeSubjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    yytHomeSubjectLambdaQueryWrapper.in(YytHomeSubject::getId,subjectIds);
                    List<YytHomeSubject> list = yytHomeSubjectService.list(yytHomeSubjectLambdaQueryWrapper);
                    hotWordLablesList = list.stream().map(yytHomeSubject -> {
                        HotWordLables hotWordLables = new HotWordLables();
                        hotWordLables.setHotId(yytHomeSubject.getId());
                        hotWordLables.setHotName(yytHomeSubject.getName());
                        return hotWordLables;
                    }).collect(Collectors.toList());
                }
                // 品牌
                YytPmsBrand yytPmsBrand = yytPmsBrandService.selectYytPmsBrandById(iYytPmsSpuInfo.getBrandId());
                // 店铺
                YytShop yytShop = yytShopService.selectYytShopById(iYytPmsSpuInfo.getShopId());
                //分类
                YytBaseCatalog yytBaseCatalog = yytBaseCatalogService.selectYytBaseCatalogById(iYytPmsSpuInfo.getCatalogId());
                // 封装 EsSkuInfo
                for (YytPmsSkuInfo iYytPmsSkuInfo : yytPmsSkuInfos) {
                    EsSkuInfo esSkuInfo = new EsSkuInfo();
                    esSkuInfo.setSkuId(iYytPmsSkuInfo.getSkuId());
                    esSkuInfo.setSkuPrice(iYytPmsSkuInfo.getPrice());
                    esSkuInfo.setSkuTitle(iYytPmsSkuInfo.getSkuTitle());
                    esSkuInfo.setLinePrice(iYytPmsSkuInfo.getLinePrice());
                    esSkuInfo.setSkuType(iYytPmsSkuInfo.getSkuType());
                    esSkuInfo.setSkuServiceType(iYytPmsSkuInfo.getSkuServiceType());
                    if (StringUtils.isNotEmpty(iYytPmsSkuInfo.getSkuDefaultImg())) {
                        esSkuInfo.setSkuImg(iYytPmsSkuInfo.getSkuDefaultImg());
                    } else {
                        LambdaQueryWrapper<YytPmsSkuImages> skuImagesLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        skuImagesLambdaQueryWrapper.eq(YytPmsSkuImages::getSkuId, iYytPmsSkuInfo.getSkuId()).eq(YytPmsSkuImages::getDefaultImg, "1");
                        YytPmsSkuImages one = yytPmsSkuImagesService.getOne(skuImagesLambdaQueryWrapper);
                        esSkuInfo.setSkuImg(one.getImgUrl());
                    }
                    esSkuInfo.setSpuId(iYytPmsSpuInfo.getId());
                    if (yytPmsBrand != null) {
                        esSkuInfo.setBrandId(yytPmsBrand.getId());
                        esSkuInfo.setBrandName(yytPmsBrand.getName());
                        esSkuInfo.setBrandImg(yytPmsBrand.getLogo());
                    }
                    if (yytShop != null) {
                        esSkuInfo.setStoreId(yytShop.getId());
                        esSkuInfo.setStoreName(yytShop.getShopName());
                    }
                    if (yytBaseCatalog != null) {
                        esSkuInfo.setCatalogId(yytBaseCatalog.getId());
                        esSkuInfo.setCatalogImage(yytBaseCatalog.getIcon());
                        esSkuInfo.setCatalogName(yytBaseCatalog.getName());
                    }
                    esSkuInfo.setHotWordLables(hotWordLablesList);
                    skuInfoList.add(esSkuInfo);
                }
            } else if (type.equals("0")) {
                elasticSearchService.deleteEs(iYytPmsSpuInfo.getId());
            }
        }

        if (type.equals("1")) {
            elasticSearchService.saveEs(skuInfoList);
        }
        boolean b = super.updateBatchById(yytPmsSpuInfos);
        if (b) {
            return 1;
        }
        return 0;
    }


}
